<template>
  <el-card>
    <template #header>
      <h2>服务关注 - 客户【{{ customerName }}】</h2>
    </template>

    <!-- 护理服务表格 -->
    <el-table :data="plans" stripe style="margin-top:16px;">
      <!-- 序号 -->
      <el-table-column
        type="index"
        width="60"
        label="序号"
        align="center"
        header-align="center"
      />
      <!-- 项目编号 -->
      <el-table-column
        prop="careProjectCode"
        label="项目编号"
        width="120"
        align="center"
        header-align="center"
      />
      <!-- 项目名称 -->
      <el-table-column
        prop="projectName"
        label="项目名称"
        align="center"
        header-align="center"
      />
      <!-- 价格 -->
      <el-table-column
        prop="price"
        label="价格"
        width="100"
        align="center"
        header-align="center"
      />
      <!-- 原有数量 -->
      <el-table-column
        prop="quantity"
        label="数量"
        width="80"
        align="center"
        header-align="center"
      />
      <!-- 到期时间 -->
      <el-table-column
        prop="expireDate"
        label="服务到期时间"
        width="160"
        align="center"
        header-align="center"
      />
	  
	  <!-- 来源 -->
	  <el-table-column
	    prop="source"
	    label="来源"
	    width="100"
	    align="center"
	    header-align="center"
	  >
	    <template #default="{ row }">
	      <el-tag type="info" effect="plain">
	        {{ row.source === 1 ? '级别项目' : row.source === 2 ? '单独购买' : '未知' }}
	      </el-tag>
	    </template>
	  </el-table-column>
	  
      <!-- 状态列 -->
      <el-table-column
        label="状态"
        width="200"
        align="center"
        header-align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row._qtyStatus.type" effect="plain" style="margin-right:4px">
            {{ row._qtyStatus.label }}
          </el-tag>
          <el-tag :type="row._expStatus.type" effect="plain">
            {{ row._expStatus.label }}
          </el-tag>
        </template>
      </el-table-column>
	  
      <!-- 操作 -->
      <el-table-column
        label="操作"
        width="180"
        align="center"
        header-align="center"
      >
        <template #default="{ row }">
          <el-button
            type="success"
            size="small"
            @click="openRenewDialog(row)"
          >续费</el-button>
          <el-button
            type="danger"
            size="small"
            @click="removePlan(row)"
          >移除</el-button>
        </template>
      </el-table-column>
    </el-table>
	
	<el-pagination
	  style="margin: 20px 0 10px; text-align: right"
	  background
	  layout="total, sizes, prev, pager, next, jumper"
	  :current-page="cur"
	  :page-size="number"
	  :page-sizes="[3, 5, 7, 10]"
	  :total="total"
	  @current-change="handlePageChange"
	  @size-change="handleSizeChange"
	/>

    <el-button style="margin-top:16px;" @click="goBack">返回列表</el-button>

    <!-- 续费对话框 -->
    <el-dialog
      title="续费护理项目"
      v-model="renewDialogVisible"
      width="500px"
    >
      <el-form :model="renewForm" label-width="120px">
        <el-form-item label="项目编号">
          <el-input v-model="renewForm.careProjectCode" disabled />
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="renewForm.projectName" disabled />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="renewForm.price" disabled />
        </el-form-item>
        <el-form-item label="原有数量">
          <el-input-number v-model="renewForm.quantity" disabled />
        </el-form-item>
        <el-form-item label="新增数量">
          <el-input-number
            v-model="renewForm.addQty"
            :min="1"
            @change="updateTotal"
          />
        </el-form-item>
        <el-form-item label="总数量">
          <el-input-number v-model="renewForm.totalQty" disabled />
        </el-form-item>
        <el-form-item label="新到期时间">
          <el-date-picker
            v-model="renewForm.newExpire"
            type="date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRenew">确认续费</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import qs from 'qs'

const axios = inject('axios')
const route = useRoute()
const router = useRouter()

// 添加分页数据
const cur = ref(1)
const number = ref(10)
const total = ref(0)

const customerId = Number(route.query.customerId)
const customerName = route.query.customerName || ''

// 主表数据
const plans = ref([])

// 续费对话框
const renewDialogVisible = ref(false)
const renewForm = reactive({
  id: null,
  careProjectCode: '',
  projectName: '',
  price: 0,
  quantity: 0,
  addQty: 1,
  totalQty: 0,
  newExpire: ''
})

function computeQuantityStatus(plan) {
  return plan.quantity <= 0
    ? { label: '欠费', type: 'danger' }
    : { label: '数量正常', type: 'success' }
}
function computeExpireStatus(plan) {
  const now = new Date()
  const exp = new Date(plan.expireDate)
  return exp < now
    ? { label: '到期', type: 'info' }
    : { label: '未到期', type: 'warning' }
}

// 替换 fetchPlans 方法
async function fetchPlans() {
  const { data: resp } = await axios.get('/CustomerCarePlanController/searchCustomerCarePlanPage', {
    params: {
      customerId,
      cur: cur.value,
      number: number.value
    }
  })
  total.value = resp.total

  plans.value = resp.data.map(p => {
    const q = computeQuantityStatus(p)
    const e = computeExpireStatus(p)
    return {
      ...p,
      _qtyStatus: q,
      _expStatus: e
    }
  })
}

function handlePageChange(page) {
  cur.value = page
  fetchPlans()
}

function handleSizeChange(size) {
  number.value = size
  cur.value = 1 // 每页数变更时，重置页码
  fetchPlans()
}

// 返回列里用的 tag 类型
function tagType(row) {
  return row._tagType
}

// 打开续费弹窗
function openRenewDialog(row) {
  renewForm.id = row.id
  renewForm.careProjectCode = row.careProjectCode
  renewForm.projectName = row.projectName
  renewForm.price = row.price
  renewForm.quantity = row.quantity
  renewForm.addQty = 1
  renewForm.totalQty = row.quantity + 1
  renewForm.newExpire = row.expireDate
  renewDialogVisible.value = true
}

// 每次新增数量改变时更新总数量
function updateTotal(val) {
  renewForm.totalQty = renewForm.quantity + val
}

// 确认续费
async function confirmRenew() {
  if (!renewForm.newExpire) {
    return ElMessage.warning('请选择新到期时间')
  }
  await axios.post('/CustomerCarePlanController/updateCustomerCarePlan', qs.stringify({
    id: renewForm.id,
    quantity: renewForm.totalQty,
    expireDate: renewForm.newExpire
  }))
  ElMessage.success('续费成功')
  renewDialogVisible.value = false
  fetchPlans()
}

// 移除
async function removePlan(row) {
  await ElMessageBox.confirm('确认移除该服务项目？', '警告', { type: 'warning' })
  await axios.delete('/CustomerCarePlanController/delCustomerCarePlan', {
    params: { customerId, careProjectCode: row.careProjectCode }
  })
  ElMessage.success('移除成功')
  fetchPlans()
}

function goBack() {
  router.push({ path: '/CustomerList', query: {} })
}

onMounted(fetchPlans)
</script>

<style scoped>
/* 如果需要额外微调对齐，可在这里写 */
</style>
